// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
    const message = cloud.getWXContext()
    let gods = await db.collection('gods').where({
        _openid: message.OPENID
    }).get()
    let roomIdList = gods.data[0].chat_list
    let list = []
    for (let i in roomIdList) {
        let item = await db.collection('chatroom').doc(roomIdList[i]).get()
        if (item.data.hold.id == message.OPENID) {  //我是持有者  hold
            // item.data.list.forEach(element => {
            //     if (element.post == message.OPENID) {
            //         element.post = "me"
            //     } else {
            //         element.post = "you"
            //     }
            // });

            list.push({
                mes: item.data.want,
                data: item.data.list
            })
        } else if (item.data.want.id == message.OPENID) { //我是want
            // item.data.list.forEach(element => {
            //     if (element.post == message.OPENID) {
            //         element.post = "you"
            //     } else {
            //         element.post = "me"
            //     }
            // });

            list.push({
                mes: item.data.hold,
                data: item.data.list
            })
        } else {
            return "404"
        }
    }
    return list
}